package com.cby.widget.sample

import android.os.Bundle
import android.util.Log
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import com.cby.widget.lib.kotlin.*

import androidx.fragment.app.Fragment


/**
 * @description: CommonActivity
 *
 * @author ChenBaoyang
 * @date 2021/10/3 13:45
 */
class CommonActivity : AppCompatActivity() {

    private lateinit var container: FrameLayout

    private val contentView by lazy {

        LinearLayout {
            layout_width = match_parent
            layout_height = match_parent
            orientation = vertical

            container = FrameLayout {
                id = R.id.common_container
                layout_width = match_parent
                layout_height = match_parent
            }
        }
    }

    private lateinit var className: String
    private lateinit var title: String

    companion object{
        const val keyName = "fragment_name"
        const val keyTitle = "fragment_title"
        const val fragmentClass = "androidx.fragment.app.Fragment"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(contentView)

        parseArgs()
        supportActionBar?.title = title
        val clz = Class.forName(className)
        if(clz.genericSuperclass.toString().contains(fragmentClass)){
            bindFragment()
        }else{
            start(clz)
        }

    }

    private fun parseArgs() {
        className = intent.getStringExtra(keyName).toString()
        title = intent.getStringExtra(keyTitle).toString()
    }

    private fun bindFragment() {
        val fm = supportFragmentManager
        val transaction = fm.beginTransaction()
        transaction.replace(R.id.common_container, getFragment())
        transaction.commit()
    }

    private fun getFragment(): Fragment {
        val clz = Class.forName(className)
        //获取构造器
        val constructor = clz.getConstructor()
        //根据构造器，实例化出对象
        val fragment = constructor.newInstance()
        return fragment as Fragment
    }
}